package com.example.gpstest.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.gpstest.R;
import com.example.gpstest.Utils.ExcelUtil;
import com.example.gpstest.Utils.KmlUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GPSGoogleEarthActivity extends AppCompatActivity {

    @BindView(R.id.tv_longitude)
    TextView tvLongitude;
    @BindView(R.id.tv_latitude)
    TextView tvLatitude;
    @BindView(R.id.tv_height)
    TextView tvHeight;
    @BindView(R.id.tv_speed)
    TextView tvSpeed;
    @BindView(R.id.btn_state_stop)
    Button btnStateStop;
    @BindView(R.id.tv_gpscontent)
    TextView tvGpscontent;

    private LocationManager locationManager;
    private ArrayList<String> locationList = new ArrayList();
    Boolean bState = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gpsgoogle_earth);
        ButterKnife.bind(this);
        initLocation();
    }

    @SuppressLint("MissingPermission")
    private void initLocation() {
        if (locationManager == null) {
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        }
        //判断GPS是否正常启动
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS导航", Toast.LENGTH_SHORT).show();
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            return;
        }
        //5000位最小的时间间隔，1为最小位移变化；也就是说每隔5000ms会回调一次位置信息
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 3, locationListener);
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            float speed = location.getSpeed();
            double height = location.getAltitude();
            tvLongitude.setText(longitude + "");
            tvLatitude.setText(latitude + "");
            tvHeight.setText(height + "");
            tvSpeed.setText(speed + "");
            tvGpscontent.setText("GPS准备就绪");
            if (bState) {
                locationList.add(longitude + "," + latitude + "," + height);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    @OnClick(R.id.btn_state_stop)
    public void onViewClicked() {
        if (btnStateStop.getText().toString().equals("开始跟踪")) {
            if (locationList.size() != 0) {
                locationList.clear();
            }
            String longitude = tvLongitude.getText().toString();
            String latitude = tvLatitude.getText().toString();
            String Height = tvHeight.getText().toString();
            String str = longitude + "," + latitude + "," + Height;
//            locationList.add("121.4455273391,31.13954599638,75.9");
//            locationList.add("121.4485273391,31.13954599638,75.9");
//            locationList.add("121.4485273391,31.13994599638,75.9");
//            btnStateStop.setText("停止跟踪");
            if (!longitude.isEmpty()) {
                locationList.add(str);
                bState = true;
                btnStateStop.setText("停止跟踪");
            } else {
                ExcelUtil.ShortToast(GPSGoogleEarthActivity.this, "GPS定位失败");
                return;
            }
        } else {
            btnStateStop.setText("开始跟踪");
            bState = false;
            String kmlName = KmlUtils.getStringDates() + ".kml";
            new XPopup.Builder(this)
                    .asInputConfirm("保存", "默认保存的路径地址:/storage/emulated/0/GPSGoogleEarth/", kmlName, null,
                            new OnInputConfirmListener() {
                                @Override
                                public void onConfirm(String text) {
                                    if (text.contains(".kml")) {
                                        String filePath = Environment.getExternalStorageDirectory().getPath() + "/GPSGoogleEarth";
                                        File files = new File(filePath);
                                        if (!files.exists()) {
                                            if (files.mkdirs()) {

                                            } else {
                                                ExcelUtil.ShortToast(GPSGoogleEarthActivity.this, "GPSGoogleEarth文件创建失败");
                                                return;
                                            }
                                        }
                                        try {
                                            KmlUtils.TravelsKml(locationList, text, GPSGoogleEarthActivity.this);
                                        } catch (Exception e) {
                                            ExcelUtil.ShortToast(GPSGoogleEarthActivity.this, "保存格式失败，换个名称");
                                            e.printStackTrace();
                                        }
                                    } else {
                                        ExcelUtil.ShortToast(GPSGoogleEarthActivity.this, "保存失败，不是kml文件格式");
                                    }
                                }
                            })
                    .show();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
            locationManager = null;
        }
    }
}
